<template>
  <div class="spec-preview">
    <!-- 异步数据有延迟,刚开始显示undefind,然后点imgurl会报错,不影响渲染,  使用问号处理 -->
    <img :src="skuImageList[bigImgIndex]?.imgUrl" />
    <div class="event" @mousemove="ZoomMove" ref="oEvent"></div>
    <div class="big">
      <img :src="skuImageList[bigImgIndex]?.imgUrl" ref="bigImg"/>
    </div>
    <div class="mask" ref="oMask"></div>
  </div>
</template>

<script>
  export default {
    name: "Zoom",
    props:['skuImageList'],
    //如果需要大图的每张对应小图,设置一个值,
    // 使用事件的时候让index为大图的值即可显示
    data(){
      return{
        bigImgIndex:0
      }
    },
    mounted(){
      this.$bus.$on('changeBigImgIndex',(index)=>{
        this.bigImgIndex = index
      })
    },

    methods:{
      //拿到even空白蒙版的事件，避免在小蒙版上处理，因为会获取当前点击的元素的距离
      ZoomMove(e){
        // console.log(e);
        //获取鼠标在当前元素边缘的XY距离
        let mouseX = e.offsetX
        let mouseY = e.offsetY
        // 计算放大镜蒙版的移动距离
        let oMask = this.$refs.oMask
        let maskX = mouseX - oMask.offsetWidth/2
        let maskY = mouseY - oMask.offsetHeight /2
        
        // 判断边距
        // 获取外层元素的
        let oEvent = this.$refs.oEvent
        if(maskX<0){
          maskX = 0
        }else if(maskX>= oEvent.clientWidth-oMask.offsetWidth){
            maskX = oEvent.clientWidth-oMask.offsetWidth
        }

        if(maskY<0){
          maskY= 0
        }else if(maskY>=oEvent.clientHeight-oMask.offsetHeight){
            maskY = oEvent.clientHeight-oMask.offsetHeight
        }

        oMask.style.left = maskX + 'px'
        oMask.style.top = maskY + 'px'

        //大图的移动相反
        this.$refs.bigImg.style.left  = -2 * maskX + "px"
        this.$refs.bigImg.style.top  = -2 * maskY+ "px"
      }
    }
  }
</script>

<style lang="less">
  .spec-preview {
    position: relative;
    width: 400px;
    height: 400px;
    border: 1px solid #ccc;

    img {
      width: 100%;
      height: 100%;
    }

    .event {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 998;
    }

    .mask {
      width: 50%;
      height: 50%;
      background-color: rgba(0, 255, 0, 0.3);
      position: absolute;
      left: 0;
      top: 0;
      display: none;
    }

    .big {
      width: 100%;
      height: 100%;
      position: absolute;
      top: -1px;
      left: 100%;
      border: 1px solid #aaa;
      overflow: hidden;
      z-index: 998;
      display: none;
      background: white;

      img {
        width: 200%;
        max-width: 200%;
        height: 200%;
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    .event:hover~.mask,
    .event:hover~.big {
      display: block;
    }
  }
</style>